package com.qf.controller;

import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qf.entity.Goods;
import com.qf.result.ResultMsg;
import com.qf.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 刘亚康
 * @Date 2020/3/28
 * @Version 1.0'
 * @Description
 */
@Slf4j
@Controller
@RequestMapping("goods")
public class GoodsControoler {
    @Autowired
    private FastFileStorageClient client;

    @Value("${FdfsUrlPath}")
    private String FdfsUrlPath;

    @Value("${uploadUrlPath}")
    private String uploadUrlPath;

    private String uploadPath = "D:\\Java\\ShopProject\\Shop_Web\\Shop_Back\\src\\main\\resources\\static\\GoodsImg";
    @Reference

    private IGoodsService goodsService;

    /**
     * 分页查询商品
     *
     * @param page
     * @param map
     * @return 商品管理页面
     */
    @RequestMapping("/getAllGoods")
    public String getAllGoods(Page<Goods> page, ModelMap map) {
        Page<Goods> dubboPage = goodsService.getDubboPage(page);
        map.put("url", "goods/getAllGoods");
        map.put("page", dubboPage);
        return "goods/goodsList";
    }

    /**
     * 图片上传本地
     *
     * @param file
     * @return 图片链接
     */
    //@RequestMapping("uploadGoodsPic")
    @ResponseBody
    public String uploadGoodsPic(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        log.info("文件名称：" + fileName);
        //图片的相对路径
        String goodsImgUrlPath = uploadUrlPath + fileName;
        InputStream ips = null;
        FileOutputStream ops = null;
        File opsFile = new File(uploadPath + File.separator + fileName);
        try {
            ips = file.getInputStream();
            //指定图片输出的路径
            ops = new FileOutputStream(opsFile);

            //IO流的拷贝
            IOUtils.write(ips, ops);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ops != null) {
                try {
                    ops.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ips != null) {
                try {
                    ips.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return goodsImgUrlPath;
    }

    /**
     * 文件上传到分布式文件管理器FastDFS
     *
     * @param file
     * @return
     */
    @RequestMapping("uploadGoodsPic")
    @ResponseBody
    public String goodsImgByFDfs(MultipartFile file) {
        StorePath storePath = null;
        try {
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String FileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

            storePath = client.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), FileExt, null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return FdfsUrlPath + storePath.getFullPath();
    }

    /**
     * 添加商品
     *
     * @return 返回结果
     */
    @RequestMapping("addGoods")
    @ResponseBody
    public ResultMsg addGoods(Goods goods) {
        log.info("请求添加商品");
        if (goods.getGoodsDesc() == "") {
            log.info("商品介绍为空");
            goods.setGoodsDesc("暂无商品说明");
        }
        log.info("添加的商品为:" + goods);
        int result = goodsService.add(goods);
        if (result > 0) {
            return ResultMsg.success();
        } else {
            return ResultMsg.fail();
        }
    }

    /**
     * 根据id删除商品
     * @param id
     * @return
     */
    @RequestMapping("delGoods/{id}")
    @ResponseBody
    public ResultMsg delGoods(@PathVariable("id") Integer id){
        log.info("要删除的商品id为："+id);
        int result = goodsService.delete(id);
        if (result>0) {
            log.info(id+"删除成功");
            return ResultMsg.success();
        }else {
            return ResultMsg.fail();
        }
    }

    @RequestMapping("batchDelGoods")
    @ResponseBody
    public ResultMsg batchDelGoods(@RequestParam("goodsId[]")List<Integer> goodsIdList){
        int resultNum=0;
        log.info("批量删除商品："+goodsIdList.toString()+"需要删除"+goodsIdList.size()+"个商品");
        for (Integer goodsId : goodsIdList) {
            int result = goodsService.delete(goodsId);
            resultNum+=result;
        }
        log.info("删除了"+resultNum+"个商品");
        if (resultNum==goodsIdList.size()) {
            return ResultMsg.success();
        }else {
            return ResultMsg.fail();
        }
    }


}
